package com.sls.api.game.servlet.enfu;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.sls.api.game.pojo.EnfuServerInfo;
import com.sls.api.game.servlet.SuperServlet;
import com.sls.api.util.IpUtil;
import com.sls.api.util.PropertiesUtil;
import com.sls.api.util.ResponseDataXmlFormat;
import com.sls.api.util.UtilMD5Encryption;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.SocketDTO;

/**
 * 
 * @description 恩付交易订单退款通知
 * @author Wangxuegang
 * @date 2013-5-3
 */
public class EnfuRefundServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(EnfuRefundServlet.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"GBK");
		resp.setContentType("text/html;charset=GBK");
		resp.setStatus(HttpServletResponse.SC_OK);

		// 合作平台编号
		String partnerId = req.getParameter("partnerId");
		// 合作方平台订单编号
		String ptOrderNo = req.getParameter("ptOrderNo");
		// SUP平台订单号
		String supOrderNo = req.getParameter("supOrderNo");
		// SUP平台退款种类
		String reType = req.getParameter("reType");
		// 退款金额
		String rePrice = req.getParameter("rePrice");
		// 退款的卡密张数
		String reNum = req.getParameter("reNum");
		// 签名字符串
		String sign = req.getParameter("sign");
		String partnerKey = PropertiesUtil.getValue("enfu.md5.key");
		boolean flag = checkData(partnerId, ptOrderNo, supOrderNo, reType,
				rePrice, reNum, sign, partnerKey, resp);
		if (flag) {
			try {
				Gson gson = CommonUtil.gson();
				SocketDTO socketChangeVo = createMsg(partnerId, ptOrderNo,
						supOrderNo, reType, rePrice, reNum, sign, req);
				Head head = socketChangeVo.getHead();
				String resCode = head.getResponseCode();
				String resMsg = head.getResponseMessage();
				resMsg = URLEncoder.encode(resMsg, "GBK"); // GBK编码

				String bodyStr = socketChangeVo.getBody();
				String resBodyStr = gson.fromJson(bodyStr, String.class);

				String xmlStr = ResponseDataXmlFormat.assembleXmlString(
						resBodyStr, resCode, resMsg);
				resp.getWriter().write(xmlStr);
				resp.getWriter().flush();
				resp.getWriter().close();
			} catch (Exception e) {
				log.error("出错", e);
				ResponseDataXmlFormat.returnResMsg("201", "其他错误", resp);
			}
		}

	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	private boolean checkData(String partnerId, String ptOrderNo,
			String supOrderNo, String reType, String rePrice, String reNum,
			String sign, String partnerKey, HttpServletResponse resp)
			throws IOException {
		boolean flag = false;
		// 合作平台编号
		if ("".equals(partnerId) || partnerId == null) {
			log.info("合作平台编号为空");
			ResponseDataXmlFormat
					.returnResMsg("101", "缺少必需参数[partnerId]", resp);
		}
		// 合作方平台订单编号
		else if ("".equals(ptOrderNo) || ptOrderNo == null) {
			log.info("合作方平台订单编号为空");
			ResponseDataXmlFormat
					.returnResMsg("101", "缺少必需参数[ptOrderNo]", resp);
		}
		// SUP平台订单号
		else if ("".equals(supOrderNo) || supOrderNo == null) {
			log.info("SUP平台订单号为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[supOrderNo]",
					resp);
		}
		// SUP平台退款种类
		else if ("".equals(reType) || reType == null) {
			log.info("SUP平台退款种类为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[reType]", resp);
		}
		// 退款金额
		else if ("".equals(rePrice) || rePrice == null) {
			log.info("退款金额为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[rePrice]", resp);
		}
		// 签名字符串
		else if ("".equals(sign) || sign == null) {
			log.info("签名字符串为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[sign]", resp);
		} else {
			StringBuilder strbu = new StringBuilder();
			strbu.append("partnerId");
			strbu.append(partnerId);
			strbu.append("ptOrderNo");
			strbu.append(ptOrderNo);
			if (reNum != null && !("".equals(reNum))) {
				strbu.append("reNum");
				strbu.append(reNum);
			}
			strbu.append("rePrice");
			strbu.append(rePrice);
			strbu.append("reType");
			strbu.append(reType);
			strbu.append("supOrderNo");
			strbu.append(supOrderNo);
			strbu.append(partnerKey);
			String data = strbu.toString().trim();

			boolean checkRes = UtilMD5Encryption.checkMD5Signature(data, sign);
			if (checkRes) {
				flag = true;
			} else {
				log.info("MD5数字签名未通过");
				flag = false;
				ResponseDataXmlFormat.returnResMsg("102", "签名失败", resp);
			}
		}

		return flag;
	}

	/**
	 * 
	 * @param partnerId
	 * @param ptOrderNo
	 * @param supOrderNo
	 * @param reType
	 * @param rePrice
	 * @param reNum
	 * @param sign
	 * @param req
	 * @return
	 */
	private SocketDTO createMsg(String partnerId, String ptOrderNo,
			String supOrderNo, String reType, String rePrice, String reNum,
			String sign, HttpServletRequest req) {
		EnfuServerInfo goodsInfo = new EnfuServerInfo();
//		goodsInfo.setPartnerId(partnerId);
//		goodsInfo.setPtOrderNo(ptOrderNo);
//		goodsInfo.setSupOrderNo(supOrderNo);
//		goodsInfo.setReType(reType);
//		goodsInfo.setRePrice(rePrice);
//		goodsInfo.setReNum(reNum);
//		goodsInfo.setSign(sign);

		SocketDTO socketChangeVo = new SocketDTO();
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(""); // =================??????????????????????????待完善
		head.setIp(IpUtil.getIpAddr(req)); // ---------坚果网络IP
		head.setUserId("0"); // ---------坚果网络用户ID
		socketChangeVo.setHead(head); // 报文头部
		return super.send(head, goodsInfo);
	}

}
